/* eslint-disable @typescript-eslint/no-explicit-any */
import { nextTick, ref, watch, type Ref } from 'vue'
import type {
  BusinessSelectorProps,
  SelectionEmits
} from './chooseServiceDialogType'
import type { QueryWrapper } from '@/types/wrappertypes'
import { OrderEnums } from '@/types/wrapper-enums'

export const useBusinessSelector = (props: BusinessSelectorProps, emit: SelectionEmits, chooseServiceDialogTableRef: Ref) => {
  const dialogVisible = ref(false)
  const tableData = ref<any[]>([])
  const selectedData = ref<any[]>([])
  const loading = ref(false)

  // 分页相关
  const currentPage = ref(1)
  const pageSize = ref(props.pageSize || 10)
  const total = ref(0)

  /**
   * NOTES ^
   * 【使用组件需阅读】
   *
   * 组件刷新逻辑：
   * 查询条件使用 QueryWrapper 构造， 可以参考对应type的属性
   * 需要传对应api async function 确定业务数据对应的目标url
   * 如果存在特殊场景，需要构造查询条件，需要在父组件中定义好QueryWrapper， 其中condition 为查询条件。
   * 默认查询条件：分页：1，10； condition：null ； sort createTime desc
   */
  const loadData = async () => {
    try {
      loading.value = true
      let queryWrapper: QueryWrapper;
      console.log(typeof props.url)
      console.log(props);
      if (props.wrapper) {
        queryWrapper = props.wrapper;
      }
      else {
        //配置默认 wrapper
        queryWrapper = {
          condition: [], //数据参数
          sort: [{ filed: 'create_time', orderType: OrderEnums.WRAPPER_ORDER_DESC }] //排序参数
        };
      }
      //更新分页
      queryWrapper.page = {
        pageNum : currentPage.value,
        pageSize: pageSize.value
      }

      const res = await props.url(queryWrapper);
      if (res.code != 200) {
        throw (res.message || "异常")
      }
      console.warn("组件查询回的数据：", res.data.rows);
      tableData.value = res.data.rows;
      total.value = res.data.total
      //加载勾选
      initSelection();
    } catch (error) {
      console.error('数据加载失败:', error)
      tableData.value = []
      total.value = 0
    } finally {
      loading.value = false
    }
  }

  const handlePageChange = (page: number) => {
    currentPage.value = page
    console.log(page);
    loadData()
  }

  const handleSizeChange = (size: number) => {
    console.log(size)
    pageSize.value = size
    currentPage.value = 1
    loadData()
  }

  watch(() => props.visible, (val) => {
    dialogVisible.value = val
    if (val) {
      currentPage.value = 1
      loadData()
    }
  })

  const handleConfirm = () => {
    const result = props.isMultiple
      ? selectedData.value
      : selectedData.value[0]
    emit('selected', result)
    dialogVisible.value = false
    selectedData.value = [];
    chooseServiceDialogTableRef.value?.clearSelection()
  }

  const handleClose = () => {
    emit('update:visible', false)
    selectedData.value = [];
    chooseServiceDialogTableRef.value?.clearSelection()
  }
  // 初始化选中状态
  const initSelection = () => {
    nextTick(() => {
      if (!props.selectIds || !chooseServiceDialogTableRef.value) return

      const ids = Array.isArray(props.selectIds) ? props.selectIds : props.selectIds.toString().split(',');
      tableData.value.forEach(row => {
        //这里默认匹配id ，如果修改 这个变量再进行调整
        const rowId = String(row['id'])
        const isSelected = ids.includes(rowId)
        if (isSelected) {
          chooseServiceDialogTableRef.value!.toggleRowSelection(row, true)
        }
      })
    })
  }

  return {
    dialogVisible,
    tableData,
    selectedData,
    loading,
    currentPage,
    pageSize,
    total,
    loadData,
    handlePageChange,
    handleSizeChange,
    handleConfirm,
    handleClose
  }
}
